use bytes::{Bytes, BytesMut};
use chrono::{Local, Datelike, Timelike};

// use crc::Algorithm;

// use crate::error::Error;

// const CRC_DEF_8_ALGO: &Algorithm<u8> = &crc::CRC_8_BLUETOOTH;

pub fn hash_crc8(payload: &BytesMut) -> u8 {
    // let payload_crc = crc::Crc::<u8>::new(CRC_DEF_8_ALGO);
    // payload_crc.checksum(payload)
    let mut ret: u8 = 0;
    let mut start: u8 = 0;
    for item in payload {
        if start == 0
        {
            ret = *item;
            start = 1;
        } else {
            ret = ret ^ *item;
        }
    }
    ret
}

pub fn hash_crc8_bytes(payload: &Bytes) -> u8 {
    // let payload_crc = crc::Crc::<u8>::new(CRC_DEF_8_ALGO);
    // payload_crc.checksum(payload)
    let mut ret: u8 = 0;
    let mut start: u8 = 0;
    for item in payload {
        if start == 0
        {
            ret = *item;
            start = 1;
        } else {
            ret = ret ^ *item;
        }
    }
    ret
}

// pub fn gw_ver_to_bytes(gw_ver: &str) -> Result<[u8; 3], Error> {
//     let v: Vec<&str> = gw_ver.split('.').collect();
//     if v.len() != 3 {
//         log::error!("Gateway version '{}' split failed", gw_ver);
//         return Err(Error::InvalidDevVer);
//     }
//     let mut ret: [u8; 3] = [0, 0, 0];
//     let mut idx = 0;
//     for item in v {
//         let aws = item.to_string().parse::<u8>();
//         if aws.is_err() {
//             log::error!("Gateway version '{}' parse failed", gw_ver);
//             return Err(Error::InvalidDevVer);
//         }
//         ret[idx] = aws.unwrap();
//         idx = idx + 1;
//     }
//     Ok(ret)
// }

pub fn fill_current_time() -> [u8;6] {
    let local_time = Local::now();
    let date_arr:[u8; 6];
    date_arr = [
        (local_time.year() - 2000) as u8,
        local_time.month() as u8,
        local_time.day() as u8,
        local_time.hour() as u8,
        local_time.minute() as u8,
        local_time.second() as u8,
    ];
    date_arr
}